package com.disapand.dingdang.service

import com.disapand.dingdang.dto.ResourceDTO
import com.disapand.dingdang.extension.page
import com.disapand.dingdang.model.Resource
import com.disapand.dingdang.model.Resources
import com.disapand.dingdang.vo.PageVO
import org.ktorm.database.Database
import org.ktorm.dsl.*
import org.springframework.stereotype.Service
import java.time.LocalDateTime

/**
 * @author disapand
 * @date 2022/2/26 - 20:42 星期六
 */
@Service
class ResourceService(private val database: Database) {

    /**
     * 分页查询资源列表
     *
     * @param dto
     * @param current
     * @param pageSize
     * @return
     */
    fun page(dto: ResourceDTO, current: Int, pageSize: Int): PageVO<Resource> {
        val query = database.from(Resources).select(Resources.columns)
            .whereWithConditions {
                if (dto.group != null) {
                    it += Resources.group like "%${dto.group}%"
                }
                if (dto.groupName != null) {
                    it += Resources.groupName like "%${dto.groupName}%"
                }
                if (dto.method != null) {
                    it += Resources.method like "%${dto.method}%"
                }
                if (dto.resource != null) {
                    it += Resources.resource like "%${dto.resource}%"
                }
                if (dto.resourceName != null) {
                    it += Resources.resourceName like "%${dto.resourceName}%"
                }
            }
            .page(current, pageSize, Resources)
        return query
    }

    /**
     * 清空所有记录
     *
     */
    fun truncate() {
        database.useConnection { connection ->
            val sql = "truncate d_resources"
            connection.prepareStatement(sql).use { statement ->
                statement.execute()
            }
        }
    }

    /**
     * 批量插入资源信息
     *
     * @param resources
     */
    fun batchSave(resources: List<Resource>) {
        database.batchInsert(Resources) {
            resources.forEach { resource ->
                item {
                    set(it.group, resource.group)
                    set(it.groupName, resource.groupName)
                    set(it.method, resource.method)
                    set(it.resource, resource.resource)
                    set(it.resourceName, resource.resourceName)
                    set(it.createdAt, LocalDateTime.now())
                }
            }
        }
    }
}
